package com.baizan.daka

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.multidex.MultiDex
import kotlin.properties.Delegates

class MyApp : Application() {

    private val TAG = "MyApp"

    companion object {
        private val activitys = ArrayList<Activity>()
        var instance: Context by Delegates.notNull()
            private set

        fun clearnAll(current: Activity? = null) {
            for (activity in activitys) {
                if (activity != current) {
                    activity.finish()
                }
            }
            activitys.clear()
            current?.let {
                activitys.add(current)
            }
        }

        fun <T : Activity> finishAct(actName: Class<T>) {
            for (activity in activitys) {
                if (activity::class.java == actName) {
                    activity.finish()
                }
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        MultiDex.install(this)
        instance = this
        registerActivityLifecycleCallbacks(a)
    }

    private var a = object : Application.ActivityLifecycleCallbacks {

        override fun onActivityPaused(activity: Activity) {
        }

        override fun onActivityStarted(activity: Activity) {
        }

        override fun onActivityDestroyed(activity: Activity) {
            activitys.remove(activity)
            Log.e(TAG, "onDestroy: " + activity.componentName.className)
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        }

        override fun onActivityStopped(activity: Activity) {
        }

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            Log.e(TAG, "onCreated: " + activity.componentName.className)
            activitys.add(activity)
        }

        override fun onActivityResumed(activity: Activity) {
        }

    }
}